#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#define size 1024
#define MAX 64


char* argv[MAX];
int lastcode = 0;
char pwd[size];
char env[size];
char* HostName()
{
  char *hostname = getenv("HOSTNAME");//得到系统中的环境变量名主机
  if(hostname)
    return hostname;
  else
    return NULL;
}

char* UserName()
{

  char *hostname = getenv("USER");
  if(hostname)
    return hostname;
  else
    return NULL;
}

char* CurrentWorkDir()
{

  char *hostname = getenv("PWD");
  if(hostname)
    return hostname;
  else
    return NULL;
}

void Split(char in[])
{
    int i = 0;
    argv[i++] = strtok(in," ");
    while(argv[i++] = strtok(NULL," "));
}

void Excute()
{
  pid_t id = fork();
  if(id == 0)
  {
    //让子进程执行
    execvp(argv[0],argv);
    //获取子进程退出码
    exit(1);
  }
  int status = 0;
  pid_t rid = waitpid(id,&status,0);
  if(rid == id) lastcode = WEXITSTATUS(status);
}

void Interactive(char* out,int SIZE)
{

    printf("[%s@%s %s]$ ",UserName(),HostName(),CurrentWorkDir());
    fgets(out,SIZE,stdin);//读取一行
    out[strlen(out) - 1] = '\0';//截取最后一个字符\n
}

char *Home()
{
    return getenv("HOME");
}

int BuildinCmd()
{
    int ret = 0;
    if(strcmp("cd", argv[0])==0)
    {
        ret = 1;
        char *target = argv[1];
        if(!target) target = Home();
        chdir(target);

        char temp[1024];
        getcwd(temp ,1024);
        snprintf(pwd,size,"PWD=%s",temp);
        putenv(pwd);
    }
    return ret;
}

int main()
{
    while(1)
    {
      // 模拟shell命令窗口
      char commandline[size];
      
      int n = 0;
      Interactive(commandline,size);
      Split(commandline);

      //处理内建命令
      BuildinCmd();
      // printf("test:%s\n",commandline);
      Excute();
    }
    return 0;
}
